<template>
  <div class="page-list-live">
    <div class="sc-page-list">
      <el-card class="box-card">
        <div v-show="!IsOnline" class="alert-warp">
          <div class="alert-banner">当前客户端离线</div>
        </div>
        <div slot="header" class="clearfix">环境监测</div>

        <el-form ref="query" :model="query" label-position="right" label-width="68px" inline>
          <el-form-item label="时间">
            <el-date-picker
              v-model="query.logTime"
              unlink-panels
              type="datetimerange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="设备名称">
            <!-- <el-input v-model="query.deviceID" style="width: 400px;"></el-input> -->
            <el-select v-model="query.deviceID" clearable filterable placeholder="请选择设备" style="width: 400px">
              <el-option v-for="item in equipmentList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item style="margin-right: 0">
            <div style="display: flex">
              <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
              <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
            </div>
          </el-form-item>
          <el-form-item style="margin-right: 0; display: block">
            <div style="display: flex">
              <el-button type="primary" icon="el-icon-search" @click="handleSearch">刷新</el-button>
            </div>
          </el-form-item>
        </el-form>

        <el-radio-group v-model="minute" style="position: absolute; margin-left: 30px; z-index: 1">
          <el-radio-button :label="1">1M</el-radio-button>
          <el-radio-button :label="5">5M</el-radio-button>
          <el-radio-button :label="30">30M</el-radio-button>
          <el-radio-button :label="60">1H</el-radio-button>
          <el-radio-button :label="1440">24H</el-radio-button>
        </el-radio-group>

        <macarons id="environmentalEcharts1" ref="environmentalEcharts1" :company-arr="companyArr" :minute="minute" :series="seriesEchartsReal" />

        <el-button icon="el-icon-delete" type="danger" style="margin-top: 20px" @click="batchDeletion">批量删除</el-button>
      </el-card>
      <el-card class="boxOne-card">
        <el-table :data="tableData" border center :header-cell-style="{ backgroundColor: '#d3dbeb' }" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column type="index" align="center" label="序号" width="60" />
          <el-table-column prop="deviceID" align="center" label="设备名称" min-width="120" />
          <el-table-column prop="label" align="center" label="监测项" min-width="120" />
          <el-table-column prop="trackingValue" align="center" label="监测值" min-width="120" />
          <el-table-column prop="unit" align="center" label="单位" min-width="120" />
          <el-table-column prop="logTime" align="center" label="时间" min-width="170">
            <template slot-scope="scope">{{ parseTime(new Date(scope.row.logTime).getTime()) }}</template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="120">
            <template slot-scope="scope">
              <el-button icon="el-icon-delete" style="color: red" size="mini" type="text" @click="handleRowDel(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="sc-list-table-pager">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pagerData.pageIndex"
            :total="pagerData.count"
            :page-size="pagerData.pageSize"
            :page-sizes="[10, 20, 30, 40, 50]"
            style="text-align: center; margin-top: 20px"
            @size-change="sizeChange"
            @current-change="currentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import macarons from './components/macarons'
import listMixin from '@/mixins/list'
import { environmentTracking, GetOnlineStatus, sensorStation } from '@/api/api'
import { parseTime } from '@/utils'

export default {
  name: 'Environmental',
  components: { macarons },
  mixins: [listMixin],
  data() {
    const startTime = parseTime(new Date().getTime() - 8.64e7 * 3, '{y}-{m}-{d}') + ' 00:00:00'
    const endTime = parseTime(new Date().getTime(), '{y}-{m}-{d}') + ' 23:59:59'
    return {
      IsOnline: true,
      deleteList: {
        id: ''
      },
      parseTime: parseTime,
      query: {
        logTime: [startTime, endTime],
        deviceID: ''
      },
      minute: 1,
      seriesEcharts: [],
      seriesEchartsReal: [],
      // 列表数据
      tableData: [],
      multipleSelection: [],
      pagerData: {
        pageIndex: 1,
        pageSize: 10,
        count: 0
      },
      // 设备下拉框
      equipmentList: [],
      // 共有多少监测项
      dictionaries: [],
      // 保存单位
      companyArr: [],
      // 保存单位
      companyArrTwo: []
    }
  },
  mounted() {
    // if (this.$route.query.name) {
    //   this.query.deviceID = this.$route.query.name
    // }
    this.handleSearch()
    this.CheckOnlinStatus()
  },

  methods: {
    async CheckOnlinStatus() {
      const res = await GetOnlineStatus()
      if (res.code === 200) {
        this.IsOnline = res.data
        console.info('  this.IsOnline', this.IsOnline)
      }
    },
    async getDataOne() {
      const obj = { pageIndex: 1, pageSize: 1e8, orderBy: 'createdTime', orderByAscent: true }
      const res = await sensorStation('post', obj, false)
      this.equipmentList = []
      res.data.items.forEach((grin) => {
        this.equipmentList.push({ label: grin.name + '(' + grin.code + ')', value: grin.code })
      })
      const resObj = res.data.items[0].settingItems
      this.companyArrTwo = resObj.map((r) => {
        return {
          label: r.label,
          value: r.labelValue
        }
      })
      this.companyArr = this.companyArrTwo
      this.setCompany(this.companyArrTwo)
    },
    setCompany(company) {
      this.seriesEcharts.forEach((item) => {
        const keylist = Object.keys(item)
        if (company.length > 0) {
          company.forEach((edit) => {
            keylist.forEach((grin) => {
              if (grin === edit.label) {
                item[grin] = item[grin] ? item[grin] + edit.value : ''
              }
            })
          })
        } else {
          keylist.forEach((grin) => {
            item[grin] = item[grin] ? item[grin] : ''
          })
        }
      })
      this.pagination()
    },
    async handleSearch(valueData) {
      this.tableLoading = true
      const query = { pageIndex: 1, pageSize: 1e8, orderBy: 'createdTime', orderByAscent: false }
      if (this.query.logTime) {
        query.search = [
          {
            key: 'createdTime',
            value: this.query.logTime[0],
            operation: 4,
            sequence: 0
          },
          {
            key: 'createdTime',
            value: this.query.logTime[1],
            operation: 5,
            sequence: 1
          },
          {
            key: 'deviceID',
            value: this.query.deviceID,
            operation: 6,
            relationship: 0,
            sequence: 2
          }
        ]
      }
      this.$refs.environmentalEcharts1.myChart.showLoading({
        text: '数据正在努力加载...',
        textStyle: { fontSize: 30, color: '#444' },
        effectOption: { backgroundColor: 'rgba(0, 0, 0, 0)' }
      })

      const res = await environmentTracking('POST', query, false)
      this.seriesEcharts = []
      this.seriesEcharts = res.data.items
      this.getDataOne()
      this.seriesEchartsReal = JSON.parse(JSON.stringify(res.data.items))

      this.pagerData.count = res.data.count
      this.tableLoading = false
      if (!res.data.items.length) {
        this.$refs.environmentalEcharts1.myChart.hideLoading()
      }
    },
    handleReset() {
      Object.assign(this.$data.query, this.$options.data().query)
      Object.assign(this.$data.pagerData, this.$options.data().pagerData)
      this.handleSearch()
    },
    sizeChange(val) {
      this.pagerData.pageSize = val
      this.pagination()
    },
    currentChange(val) {
      this.pagerData.pageIndex = val
      this.pagination()
    },
    // 前端分页
    pagination() {
      const start = this.pagerData.pageIndex * this.pagerData.pageSize - this.pagerData.pageSize
      const end = this.pagerData.pageIndex * this.pagerData.pageSize
      this.tableData = this.seriesEcharts.slice(start, end)
    },
    handleRowDel({ row }) {
      const obj = { id: row.id, value: null }
      environmentTracking('delete', obj, true).then((res) => {
        this.handleSearch()
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      })
    },
    // 批量删除
    batchDeletion() {
      var that = this
      if (!this.deleteList.id) {
        this.$message.warning('请选择要删除的数据！')
        return
      }
      this.$_delConfirm('选中数据', () => {
        environmentTracking('delete', that.deleteList, true).then((res) => {
          this.handleSearch()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        })
      })
    },
    // 选中事件
    handleSelectionChange(event) {
      if (event.length > 0) {
        const ary = []
        event.forEach((item) => {
          ary.push(item.id)
        })
        if (ary.length > 1) {
          this.deleteList.id = ary.join(',')
        } else {
          this.deleteList.id = ary[0]
        }
      } else {
        this.deleteList.id = ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .clearfix {
    padding: 20px;
    box-sizing: border-box;
  }
  .boxOne-card {
    margin-top: 20px;
    ::v-deep.el-card__body {
      padding: 0px;
      padding-bottom: 20px;
    }
  }
  .sc-list-table-pager {
    ::v-deep.active {
      background-color: #254c99 !important;
      color: #fff;
    }

    .el-pagination {
      ::v-deep .el-pagination__sizes {
        .el-input.is-focus {
          .el-input__inner {
            border-color: #254c99;
            // background-color: #254c99;
          }
          .el-input__inner:hover {
            border-color: #254c99;
            // background-color: #254c99;
          }
        }
        .el-input {
          .el-input__inner:hover {
            border-color: #254c99;
            // background-color: #254c99;
          }
          .el-input__inner:focus {
            border-color: #254c99;
            // background-color: #254c99;
          }
        }
      }
      ::v-deep .el-pagination__jump {
        .el-input {
          .el-input__inner:focus {
            border-color: #254c99;
            // background-color: #254c99;
          }
        }
      }
    }
  }
</style>
